import React, { useCallback, useMemo } from 'react';
import { useContextSelector } from 'use-context-selector';

import FormLabel from '@/components/MyBox/FormLabel';
import QuestionTip from '@/components/tooltip/QuestionTip';
import NodeInputSelect from '@/components/workflow/NodeInputSelect';
import { t } from '@/locales/i18n';
import { FlowNodeInputTypeEnum } from '@/types/workflow/constant';
import { FlowNodeInputItemType } from '@/types/workflow/io';

import { WorkflowContext } from '../../../../context';
import ValueTypeLabel from '../ValueTypeLabel';

type Props = {
  nodeId: string;
  input: FlowNodeInputItemType;
};

const InputLabel = ({ nodeId, input }: Props) => {
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);

  const { description, required, label, selectedTypeIndex, renderTypeList, valueType, valueDesc } =
    input;

  const onChangeRenderType = useCallback(
    (e: string) => {
      const index = renderTypeList.findIndex((item) => item === e) || 0;

      onChangeNode({
        nodeId,
        type: 'updateInput',
        key: input.key,
        value: {
          ...input,
          selectedTypeIndex: index,
          value: undefined,
        },
      });
    },
    [input, nodeId, onChangeNode, renderTypeList],
  );

  const RenderLabel = useMemo(() => {
    const renderType = renderTypeList?.[selectedTypeIndex || 0];

    return (
      <div className="nodrag relative flex w-full cursor-default select-none items-center gap-2">
        <div className="relative flex items-center font-medium">
          <FormLabel required={required}>{t(label as any)}</FormLabel>
          {description && <QuestionTip className="ml-2" title={t(description as any)} icon="" />}
        </div>
        {/* value type */}
        {renderType === FlowNodeInputTypeEnum.reference && (
          <ValueTypeLabel valueType={valueType} valueDesc={valueDesc} />
        )}

        {renderTypeList && renderTypeList.length > 1 && (
          <div className="ml-auto">
            <NodeInputSelect
              renderTypeList={renderTypeList}
              renderTypeIndex={selectedTypeIndex}
              onChange={onChangeRenderType}
            />
          </div>
        )}
      </div>
    );
  }, [
    description,
    label,
    onChangeRenderType,
    renderTypeList,
    required,
    selectedTypeIndex,
    valueDesc,
    valueType,
  ]);

  return RenderLabel;
};

export default React.memo(InputLabel);
